#include<stdio.h>
#include<stdlib.h>
#define MAXV 1010
#define INF 9999

typedef struct Gnode{
    int V[MAXV];//顶点集
    int E[MAXV][MAXV];//边集
    int n,e;//顶点数、边数
}GNode;


GNode *CreateGraph()
{
    GNode *G;
    G=(GNode*)malloc(sizeof(GNode));
    if(G==NULL)return NULL;
    int i,j,num1,num2,cost;
    
    scanf("%d %d",&(G->n),&(G->e));
    for(i=1;i<=G->n;i++)G->V[i]=i;//顶点集初始化
    for(i=1;i<=G->n;i++){//边集初始化
        for(j=1;j<=G->n;j++){
            G->E[i][j]=INF;
        }
    }
    for(i=1;i<=G->e;i++){
        scanf("%d %d %d",&num1,&num2,&cost);
        G->E[num1][num2]=cost;
        G->E[num2][num1]=cost;
    }
    return G;
}
void Prim(GNode *G)
{
    int lowcost[MAXV];
    int count=0,min,minId,sum=0;
    int i,j;
    
    for(j=1;j<=G->n;j++){
        lowcost[j]=G->E[1][j];
    }
    
    count++;lowcost[1]=0;
    while(count<G->n){
        min=INF;minId=1;
        for(i=1;i<=G->n;i++){
            if(lowcost[i]<min && lowcost[i]!=0){
                min=lowcost[i];
                minId=i;
            }
        }

        count++;lowcost[minId]=0;sum +=min;

        for(i=1;i<=G->n;i++){
            if(lowcost[i]!=0&& G->E[minId][i]<lowcost[i]){
                lowcost[i]=G->E[minId][i];
            }
        }
    }
    if(sum>INF)printf("-1");
    else printf("%d",sum);
}
int main()
{
    GNode *G;
    G=CreateGraph();
    Prim(G);
    return 0;
}